package com.jandar;

import java.io.File;
import java.util.Date;
import java.util.Timer;

import com.jandar.logging.Logger;
import com.jandar.logging.LoggerFactory;
import com.jandar.parser.BaseParser;
import com.jandar.task.TimeTaskFactory;
import com.jandar.util.FileUtils;

/**
 * 定时器。
 * 
 * @author pqj
 * @version 2009-7-9
 */
public class Watcher {

	/** 定时器 */
	private Timer timer = null;

	/** 文件操作 */
	private FileUtils fileOperator = null;

	/** 开始时间 */
	private Date startTime = null;

	/** 间隔时间 */
	private long period;
	
	/** 定时器任务 */
	private String timeTaskName = null;

	/** 日志文件 */
	private Logger logger = null;
	
	public Watcher() throws ClassNotFoundException {
		this.timer = new Timer();
		init();
	}

	public Watcher(boolean isDemon) throws ClassNotFoundException {
		this.timer = new Timer(isDemon);
		init();
	}

	public Watcher(String name, boolean isDemon) throws ClassNotFoundException {
		this.timer = new Timer(name, isDemon);
		init();
	}

	private void init() throws ClassNotFoundException {
		// WEB方式运行时首先加载Resources
		Class.forName("com.jandar.Resources");
		Resources resources = Resources.getInstance();
		startTime = resources.getStartTime();
		period = resources.getPeriod();
		timeTaskName = resources.getTimeTask();
		
		fileOperator = FileUtils.getInstance();
		logger = LoggerFactory.getInstance(this.getClass());
	}

	public void start() {
		BaseParser.setCancelled(false);
		logger.info("文件导入定时器启动...");
		logger.info("文件导入定时器将于" + Resources.getInstance().getStartTimeStr() + "运行，每"
				+ Resources.getInstance().getPeriod() + "ms扫描一次<"
				+ fileOperator.getInfolder().getAbsolutePath() + ">目录。");
		// 不存在的话，创建该文件。
		fileOperator.isInfolderEmpty();

		timer.schedule(TimeTaskFactory.createTimeTask(timeTaskName), startTime, period);
	}

	public void stop() {
		BaseParser.setCancelled(true);
		if (timer != null) {
			logger.info("文件导入定时器关闭。");
			timer.cancel();
			timer = null;
		}
	}

	public Date getStartTime() {
		return startTime;
	}

	public long getPeriod() {
		return period;
	}

	public String getTimeTaskName() {
		return timeTaskName;
	}

	public static boolean matchFile(File file, String[] fileType) {
		String fName = file.getName().toLowerCase();
		for (String type : fileType) {
			if (fName.endsWith(type)) {
				return true;
			}
		}
		return false;
	}
}
